package io.github.wanggit.antcms.server.service.impl.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class MediaUtil {

    private static final Map<String, String> CONTENT_TYPE_2_FILE_SUBFIX = new HashMap<>();

    @Value("${application.preview.home}")
    private String previewHomeUrl;

    @Value("${application.published.home}")
    private String publishedHomeUrl;

    static {
        CONTENT_TYPE_2_FILE_SUBFIX.put("image/jpeg", "jpg");
        CONTENT_TYPE_2_FILE_SUBFIX.put("image/gif", "gif");
    }

    public String cleanPreviewUrl(String url) {
        String urlPart = url.replace(previewHomeUrl, "");
        return urlPart.startsWith("/") ? urlPart : "/" + urlPart;
    }

    public String wrapPreviewUrl(String url) {
        return url.startsWith(previewHomeUrl) ? url : previewHomeUrl + url;
    }

    public String contentTypeToFileSubfix(String contentType) {
        return CONTENT_TYPE_2_FILE_SUBFIX.get(contentType);
    }

    public String cleanPublishedUrl(String url) {
        String urlPart = url.replace(publishedHomeUrl, "");
        return urlPart.startsWith("/") ? urlPart : "/" + urlPart;
    }

    public String wrapPublishedUrl(String url) {
        return url.startsWith(publishedHomeUrl) ? url : publishedHomeUrl + url;
    }
}
